<template>
   <div class="table-fixed">
     <el-table :data="activityList" border size="small" stripe fit>
            <el-table-column prop="batchId" label="批次ID" width="100">
              <template slot-scope="{row}">
                {{row.couponsId}}
              </template>
            </el-table-column>
            <el-table-column  label="券名称" width="200">
              <template slot-scope="{$index,row}">
                <span v-if="row.batchName&&!row.edit">{{row.batchName}}</span>
                <el-input v-else v-model="row.batchName" placeholder="选择优惠券" disabled style="width: 170px;" size="small">
                  <template slot="append">
                    <el-button
                      v-if="!row.id"
                      type="text"
                      size="small"
                      style="padding: 0 10px;"
                      @click="selectedRow($index)"
                    >选择</el-button>
                  </template>
                </el-input>
              </template>
            </el-table-column>
            <el-table-column  label="活动有效期" min-width="270">
              <template slot-scope="{ row }">
                <span v-if="!row.edit">{{row.date&&row.date.join('-')}}</span>
                <div v-else class="item-datepicker-wrapper">
                  <el-date-picker
                    v-model="row.date"
                    size="small"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format="yyyy-MM-dd"
                  ></el-date-picker>
                </div>
              </template>
            </el-table-column>
            <el-table-column  label="每人领券数量" min-width="180">
              <template slot-scope="{row}">
                <span v-if="row.limitNum&&!row.edit">{{row.limitNum}}</span>
                <el-input-number :min="1"  v-else v-model.number="row.limitNum" placeholder="每人领券数量" size="small" />
              </template>
            </el-table-column>
            <el-table-column  label="活动总数量" min-width="180">
              <template  slot-scope="{row}">
                <span v-if="row.countNum&&!row.edit">{{row.countNum}}</span>
                <el-input-number ref="countRef" :min="1" v-else v-model.number="row.countNum"  placeholder="活动总数量" size="small" />
              </template>
            </el-table-column>
            <el-table-column  label="活动剩余库存" prop="countNum" width="100">
    
              <template slot-scope="{ row }">{{(!row.edit&&row.surplusNum) || row.countNum}}</template> 
            </el-table-column>
            <el-table-column  label="操作" align="center" width="150" fixed="right">
              <template slot-scope="{$index, row}">
                <el-button v-if="!row.edit&&row.couponsId" type="text" size="small" @click="edit(row)">编辑</el-button>
                <el-button v-else type="text" size="small" @click="save(row)">保存</el-button>
                <el-button type="text" size="small" @click="delRow(row.id,$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
           <div
            @click="addMore"
            style="position: fixed; bottom: 0; left: 220px; right: 10px; height: 50px; background:#f2f2f2; text-align: center; line-height: 50px; cursor: pointer;"
          >
            <span style="font-size: 16px; color: '#999'">添加新券</span>
          </div>
          <m-choice-coupon ref="mcc" @multipSelect="multipSelectCoupon"></m-choice-coupon>
   </div>
</template>
<script>
import MChoiceCoupon from './m-choice-coupon'
import { addReceive,editReceive,delReceive,queryList } from '@/api/coupon/configcenter'

export default {
  components:{ MChoiceCoupon },
  data(){
    return {
      selectedIndex:0,
      activityList:[],
    }
  },
  created() {
    this.getList()
  },
  mounted(){
  },
  methods: {
    selectedRow(i){
      this.selectedIndex = i
      this.$refs.mcc.visible = true
    },
    // 列表查询
    getList(){
      queryList(2).then(res=>{
        const { result } = res
        console.log(res);
        if(result){
          this.activityList = result.map(v => {
            v.edit = false
            v.couponsId = v.batchId
            // v.countNum = v.totalNum
            v.countNum = v.countNum;
            if(v.startTime){
              v.date = [v.startTime,v.endTime]
            }
            return v
          })
        }
        this.activityList.push({edit:true})
        // this.$nextTick(()=>{
        //   const ref = this.$refs['countRef']
        //   console.log(ref)
        //   this.$watch('$refs.countRef.userInput',function(val){
        //     console.log(val)
        //   })
        //   // ref.$on('input',(val)=>{
        //   //   console.log(val)
        //   // })
        // })
      })
    },
    multipSelectCoupon(val){
      if(val&&val.length>0){
        const editIndex = []
        this.activityList.forEach((v,i) => {
          if( i === this.selectedIndex){
            editIndex.unshift(i)
          }
          if(v.edit&&!v.id && i !== this.selectedIndex){
            editIndex.push(i)
          }
        })
        val.forEach((item,i) => {
          const obj = {
                id:'',
                couponsId:item.couponsId,
                batchName:item.batchName,
                edit:true,
                orderSrot:0,
                surplusNum:item.stockNum,
                countNum:item.stockNum
                
            }
          if(editIndex&&editIndex[i]){
            const os = Object.assign({},this.activityList[editIndex[i]],obj)
             this.$set(this.activityList,editIndex[i],os)
          }else{
            let l = this.activityList.length
            this.$set(this.activityList,l,obj)
          }
        })
      }
    },
    // 保存
    async save(row){
      if(!row.couponsId) return this.$message.error('请选择优惠卷！')
      if(!row.date) return this.$message.error('请选择活动有效日期！')
      if(!row.limitNum) return this.$message.error('请输入领卷数量！')
      if(!row.countNum) return this.$message.error('请输入活动总数量！')
      row.startTime = row.date[0]|| ''
      row.endTime = row.date[1]|| ''
      try {
          let res
          if(row.id){
            res = await editReceive({
              id:row.id,
              "countNum": row.countNum,
              "endTime": row.endTime,
              "limitNum": row.limitNum,
              "orderSrot": row.orderSrot || 1,
              "startTime": row.startTime
            })
          }else{
            res = await addReceive(row)
          }
           const { result, message } = res
           if(res.code === 200){
             row.edit = false
             if(!row.id) row.id = result
             this.$message.success('保存成功')
           }else{
              this.$message.error(message)
           }
      } catch (error) {
        
      }
    },
    edit(row){
      row.edit = true
    },
    // 删除领券活动（逻辑删除）
    delRow(id,index){
      console.log(id,index)
      if(id){
        this.$confirm("确定要删除该优惠券吗？", "删除确认", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          delReceive(id).then(res => {
            if(res.code === 200){
              this.activityList.splice(index,1)
              this.$message.success('删除成功')
            }
          })
        }).catch(e=>console.log(e));
      }else{
         this.activityList.splice(index,1)
      }
     
    },
    addMore(){
      this.activityList.push({edit:true})
    }
  },

}
</script>

<style lang="scss">
.table-fixed {
  .el-table__fixed-right {
    height: 100% !important; //设置高优先，以覆盖内联样式
  }
}
</style>
